<?php
include __DIR__ . "/config/cors.php";
include __DIR__ . "/database.php";

$cookie = @$_COOKIE['role'];
$uid = @$_POST['uid'];
$username = @$_POST['username'];
$mail = @$_POST['mail'];
$role = @$_POST['role'];
$status = @$_POST['status'];

if (!isset($cookie) or $cookie != "admin") {
    echo json_encode([
        "code" => 401,
        "message" => "无权访问！"
    ]);
    exit;
} else if (!isset($username) or $username == "") {
    echo json_encode([
        "code" => 201,
        "message" => "用户名不能为空"
    ]);
    exit;
}

$db = new DB();
// 判断用户是否存在
$sql = "select * from user where id = '$uid'";
$data = $db->selectOne($sql);
if (is_array($data) and count($data) > 0) {
    if ($username != $data['username']) {
        $sql = "select * from user where username = '$username'";
        $data = $db->selectOne($sql);
        if (is_array($data) and count($data) > 0) {
            echo json_encode([
                "code" => 206,
                "message" => "该用户名已被使用"
            ]);
        } else {
            $sql = "update user set
                username = '$username', mail = '$mail', role = '$role', status = '$status'
                where id = '$uid'";
            if ($db->execute($sql)) {
                echo json_encode([
                    "code" => 200,
                    "message" => "修改用户信息成功"
                ]);
            } else {
                echo json_encode([
                    "code" => 205,
                    "message" => "修改用户信息失败"
                ]);
            }
        }

    }
} else {
    echo json_encode([
        "code" => 202,
        "message" => "用户不存在"
    ]);
}